var countRows = 1;
var dataSource;

$(document).ready(function() {
     dataSource = new kendo.data.DataSource({
        data: appBosch.data,
        schema: {
            model: {
                fields: {
                    user: { type: 'string' },
                    cat: { type: 'string' },
                    eval: { type: 'string' },

                    nomina: { type: 'string' },
                    name: { type: 'string' },
                    test: { type: 'string' },
                    level: { type: 'string' },
                    line: { type: 'string' }
                }
            }
        }
    });

    $("#grid").kendoGrid({
        toolbar: [
            {
                name: "excel",
                text: "Exportar a Excel"
            },
            {
                name: "pdf",
                text: "Exportar a PDF"
            }
        ],
        excel: {
            allPages: true,
            fileName: "Requieren aprobación.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Requieren aprobación.pdf"
        },
        scrollable: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        dataBound: function () {
            countRows = 1;
        },
        dataSource: dataSource,
        columns: [
            {title: "#", template: '#=countRows++#', width: 40 },
            {field: "nomina", title: "Nómina"},
            {field: "name", title: "Nombre"},
            {field: "line", title: "Linea"},
            {field: "test", title: "Examen"},
            {field: "level", title: "Nivel"},
            {
                field: "aproved",
                title: "Aprobar nivel",
                template: '<span class="k-button aproval">Aprobar</span>'
            }
        ]
    });

    $('#grid').on('click', '.aproval', aproveLevel);
});

function aproveLevel(e) {
    var dataItem = $(e.currentTarget).closest("tr");
    dataItem = dataSource.getByUid(dataItem.data('uid'));
    $(e.currentTarget).removeClass('aproval');
    $(e.currentTarget).html('<span class="fa fa-spin fa-spinner"></span>');
    $.post(appBosch.urlAprove, { model: kendo.stringify(dataItem)}, function (resp) {
        if (resp === 'true') {
            $(e.currentTarget).html('<span class="fa fa-check"></span>');
        } else {
            $(e.currentTarget).addClass('aproval');
        }
    });
}